package net.xiaoxiangshop.controller.shop;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import javax.inject.Inject;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import net.xiaoxiangshop.entity.*;
import net.xiaoxiangshop.service.*;
import net.xiaoxiangshop.util.XmlUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonView;

import net.xiaoxiangshop.Results;
import net.xiaoxiangshop.plugin.PaymentPlugin;
import net.xiaoxiangshop.security.CurrentCart;
import net.xiaoxiangshop.security.CurrentUser;
import net.xiaoxiangshop.util.WebUtils;

/**
 * Controller - 订单
 */
@Controller("shopOrderController")
@RequestMapping("/order")
public class OrderController extends BaseController {

    /**
     * ERP中台接口URL
     */
    @Value("${erp_basic_url}")
    private String erp_basic_url;
    //积分卡描述
    private String JIFEN_CARD_DESN="积分卡|0306";
    @Inject
    private SkuService skuService;
    @Inject
    private AreaService areaService;
    @Inject
    private ReceiverService receiverService;
    @Inject
    private PaymentMethodService paymentMethodService;
    @Inject
    private ShippingMethodService shippingMethodService;
    @Inject
    private OrderService orderService;
    @Inject
    private OrderItemService orderItemService;
    @Inject
    private PluginService pluginService;
    @Inject
    private MemberService memberService;
    @Inject
    private MemberDepositLogService memberDepositLogService;
    @Inject
    private OrderPaymentService orderPaymentService;
    @Inject
    private SnService snService;
    @Inject
    private ErpSyncService erpSyncService;

    @Inject
    private CartService  cartService;
    @Inject
    private CartItemService  cartItemService;


    /**
     * 检查SKU
     */
    @GetMapping("/check_sku")
    public ResponseEntity<?> checkSku(Long skuId, Integer quantity) {
        if (quantity == null || quantity < 1) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        Sku sku = skuService.find(skuId);
        if (sku == null) {
            return Results.unprocessableEntity("shop.order.skuNotExist");
        }
        if (Product.Type.GIFT.equals(sku.getType())) {
            return Results.unprocessableEntity("shop.order.skuNotForSale");
        }
        if (!sku.getIsActive()) {
            return Results.unprocessableEntity("shop.order.skuNotActive");
        }
        if (!sku.getIsMarketable()) {
            return Results.unprocessableEntity("shop.order.skuNotMarketable");
        }
        if (quantity > sku.getAvailableStock()) {
            return Results.unprocessableEntity("shop.order.skuLowStock");
        }
        if (sku.getProduct().getStore().hasExpired()) {
            return Results.unprocessableEntity("shop.order.skuNotBuyExpired");
        }
        return Results.OK;
    }

    /**
     * 检查购物车
     */
    @GetMapping("/check_cart")
    public ResponseEntity<?> checkCart(@CurrentCart Cart currentCart) {


        if (currentCart == null || currentCart.isEmpty()) {
            return Results.unprocessableEntity("shop.order.cartEmpty");
        }

        Set<CartItem> cartItems=currentCart.getCartItems();

        Set<CartItem> set=new HashSet<>();
        for (CartItem c:cartItems){
            if (c.getIsBuy()==1){
                set.add(c);
            }
        }
        currentCart.setCartItems(set);

        if (currentCart.hasNotActive()) {
            return Results.unprocessableEntity("shop.order.cartHasNotActive");
        }
        if (currentCart.hasNotMarketable()) {
            for (CartItem c:currentCart.getCartItems()) {
                if(!BooleanUtils.isTrue(c.getSku().getProduct().getIsMarketable())){
                    String  msg = "编号为" + c.getSku().getProduct().getInternalNumber()+ "的商品:" + c.getSku().getProduct().getName() + "已下架，暂时无法购买。";
                    ResponseEntity<Map<String, String>> UNPROCESSABLE_ENTITY = Results.unprocessableEntity(msg);
                    return UNPROCESSABLE_ENTITY;
                }
            }
//            return Results.unprocessableEntity("shop.order.cartHasNotMarketable");
        }
        if (currentCart.hasLowStock()) {
            return Results.unprocessableEntity("shop.order.cartHasLowStock");
        }
        if (currentCart.hasExpiredProduct()) {
            return Results.unprocessableEntity("shop.order.cartHasExpiredProduct");
        }

        return Results.OK;
    }

    /**
     * 收货地址列表
     */
    @GetMapping("/receiver_list")
    @JsonView(BaseEntity.BaseView.class)
    public ResponseEntity<?> receiverList(@CurrentUser Member currentUser) {
        return ResponseEntity.ok(receiverService.findList(currentUser));
    }

    /**
     * 添加收货地址
     */
    @PostMapping("/add_receiver")
    @JsonView(BaseEntity.BaseView.class)
    public ResponseEntity<?> addReceiver(Receiver receiver, Long areaId, @CurrentUser Member currentUser) {
        receiver.setArea(areaService.find(areaId));
        if (!isValid(receiver)) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (Receiver.MAX_RECEIVER_COUNT != null && currentUser.getReceivers().size() >= Receiver.MAX_RECEIVER_COUNT) {
            return Results.unprocessableEntity("shop.order.addReceiverCountNotAllowed", Receiver.MAX_RECEIVER_COUNT);
        }
        receiver.setAreaName(null);
        receiver.setMember(currentUser);
        receiverService.save(receiver);
        return ResponseEntity.ok(receiver);
    }

    /**
     * 订单锁定
     */
    @PostMapping("/lock")
    public @ResponseBody
    void lock(String[] orderSns, @CurrentUser Member currentUser) {
        for (String orderSn : orderSns) {
            Order order = orderService.findBySn(orderSn);
            if (order != null && currentUser.equals(order.getMember()) && order.getPaymentMethod() != null && PaymentMethod.Method.ONLINE.equals(order.getPaymentMethod().getMethod()) && order.getAmountPayable().compareTo(BigDecimal.ZERO) > 0) {
                orderService.acquireLock(order, currentUser);
            }
        }
    }

    /**
     * 检查等待付款
     */
    @GetMapping("/check_pending_payment")
    public @ResponseBody
    boolean checkPendingPayment(String[] orderSns, @CurrentUser final Member currentUser) {
        return ArrayUtils.isNotEmpty(orderSns) && CollectionUtils.exists(Arrays.asList(orderSns), new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                String orderSn = (String) object;
                Order order = orderService.findBySn(orderSn);

                return order != null && currentUser.equals(order.getMember()) && order.getPaymentMethod() != null && PaymentMethod.Method.ONLINE.equals(order.getPaymentMethod().getMethod()) && order.getAmountPayable().compareTo(BigDecimal.ZERO) > 0;
            }
        });
    }




    /**
     * 结算
     */
    @GetMapping("/checkout")
    public String checkout(Long skuId, Integer quantity, @CurrentUser Member currentUser, @CurrentCart Cart currentCart, ModelMap model) {
        Cart cart;
        Order.Type orderType;


        if (skuId != null) {
            Sku sku = skuService.find(skuId);
            if (sku == null) {
                return UNPROCESSABLE_ENTITY_VIEW;
            }
            if (Product.Type.GIFT.equals(sku.getType())) {
                return UNPROCESSABLE_ENTITY_VIEW;
            }
            if (quantity == null || quantity < 1) {
                return UNPROCESSABLE_ENTITY_VIEW;
            }
            cart = generateCart(currentUser, sku, quantity);

            switch (sku.getType()) {
                case GENERAL:
                    orderType = Order.Type.GENERAL;
                    break;
                case EXCHANGE:
                    orderType = Order.Type.EXCHANGE;
                    break;
                default:
                    orderType = null;
                    break;
            }
        } else {
            //过滤选中的购物车数据
            Set<CartItem> cartItem= currentCart.getCartItems();
            Set<CartItem> cartItems= new HashSet<CartItem>();
            for (CartItem c:cartItem){
                if(c.getIsBuy()==1){
                    cartItems.add(c);
                }
            }
            currentCart.setCartItems(cartItems);
            cart = currentCart;
            orderType = Order.Type.GENERAL;
        }
        if (cart == null || cart.isEmpty()) {
            return UNPROCESSABLE_ENTITY_VIEW;
        }
        if (cart.hasNotActive()) {
            return UNPROCESSABLE_ENTITY_VIEW;
        }
        if (cart.hasNotMarketable()) {
            return UNPROCESSABLE_ENTITY_VIEW;
        }
        if (cart.hasLowStock()) {
            return UNPROCESSABLE_ENTITY_VIEW;
        }
        if (cart.hasExpiredProduct()) {
            return UNPROCESSABLE_ENTITY_VIEW;
        }
        if (orderType == null) {
            return UNPROCESSABLE_ENTITY_VIEW;
        }

        Receiver defaultReceiver = receiverService.findDefault(currentUser);
        List<Order> orders = orderService.generate(orderType, cart, defaultReceiver, null, null,  null, null, null);

        BigDecimal price = BigDecimal.ZERO;
        BigDecimal fee = BigDecimal.ZERO;
        BigDecimal freight = BigDecimal.ZERO;
        BigDecimal tax = BigDecimal.ZERO;
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal amountPayable = BigDecimal.ZERO;
        Long rewardPoint = 0L;
        Long exchangePoint = 0L;
        boolean isDelivery = false;

        for (Order order : orders) {
            price = price.add(order.getPrice());
            fee = fee.add(order.getFee());
            freight = freight.add(order.getFreight());
            tax = tax.add(order.getTax());
            amount = amount.add(order.getAmount());
            amountPayable = amountPayable.add(order.getAmountPayable());
            rewardPoint = rewardPoint + order.getRewardPoint();
            exchangePoint = exchangePoint + order.getExchangePoint();
            if (order.getIsDelivery()) {
                isDelivery = true;
            }
        }

        model.addAttribute("skuId", skuId);
        model.addAttribute("quantity", quantity);
        model.addAttribute("cart", cart);
        model.addAttribute("orderType", orderType);
        model.addAttribute("defaultReceiver", defaultReceiver);
        model.addAttribute("orders", orders);
        model.addAttribute("price", price);
        model.addAttribute("fee", fee);
        model.addAttribute("freight", freight);
        model.addAttribute("tax", tax);

        model.addAttribute("amount", amount);
        model.addAttribute("amountPayable", amountPayable);
        model.addAttribute("rewardPoint", rewardPoint);
        model.addAttribute("exchangePoint", exchangePoint);
        model.addAttribute("isDelivery", isDelivery);

        List<PaymentMethod> paymentMethods = new ArrayList<>();
        if (cart.contains(Store.Type.GENERAL)) {
            CollectionUtils.select(paymentMethodService.findAll(), new Predicate() {
                @Override
                public boolean evaluate(Object object) {
                    PaymentMethod paymentMethod = (PaymentMethod) object;
                    return paymentMethod != null && PaymentMethod.Method.ONLINE.equals(paymentMethod.getMethod());
                }
            }, paymentMethods);
        } else {
            paymentMethods = paymentMethodService.findAll();
        }
        model.addAttribute("paymentMethods", paymentMethods);
        model.addAttribute("shippingMethods", shippingMethodService.findAll());

        return "shop/order/checkout";
    }

    /**
     * 计算
     */
    @GetMapping("/calculate")
    public ResponseEntity<?> calculate(Long skuId, Integer quantity, Long receiverId, Long paymentMethodId, Long shippingMethodId, String code, String invoiceTitle, String invoiceTaxNumber, BigDecimal balance, String memo, @CurrentUser Member currentUser, @CurrentCart Cart currentCart) {
        Map<String, Object> data = new HashMap<>();
        Cart cart;
        Order.Type orderType;
        if (skuId != null) {
            Sku sku = skuService.find(skuId);
            if (sku == null) {
                return Results.UNPROCESSABLE_ENTITY;
            }
            if (Product.Type.GIFT.equals(sku.getType())) {
                return Results.UNPROCESSABLE_ENTITY;
            }
            if (quantity == null || quantity < 1) {
                return Results.UNPROCESSABLE_ENTITY;
            }

            cart = generateCart(currentUser, sku, quantity);

            switch (sku.getType()) {
                case GENERAL:
                    orderType = Order.Type.GENERAL;
                    break;
                case EXCHANGE:
                    orderType = Order.Type.EXCHANGE;
                    break;
                default:
                    orderType = null;
                    break;
            }
        } else {
            cart = currentCart;
            orderType = Order.Type.GENERAL;
        }


        if (cart == null || cart.isEmpty()) {
            return Results.UNPROCESSABLE_ENTITY;
        }

        Set<CartItem> cartItemSet =cart.getCartItems();
        Set<CartItem>  itemSet=new HashSet<CartItem>();
        for (CartItem c:cartItemSet){
            if (c.getIsBuy()==1){
                itemSet.add(c);
            }
        }
        cart.setCartItems(itemSet);

        if (cart.hasNotActive()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (cart.hasNotMarketable()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (cart.hasLowStock()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (cart.hasExpiredProduct()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (orderType == null) {
            return Results.UNPROCESSABLE_ENTITY;
        }

        Receiver receiver = receiverService.find(receiverId);
        if (receiver != null && !currentUser.equals(receiver.getMember())) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (balance != null && balance.compareTo(BigDecimal.ZERO) < 0) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (balance != null && balance.compareTo(currentUser.getAvailableBalance()) > 0) {
            return Results.unprocessableEntity("shop.order.insufficientBalance");
        }
        PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
        if (cart.contains(Store.Type.GENERAL) && paymentMethod != null && PaymentMethod.Method.OFFLINE.equals(paymentMethod.getMethod())) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);

        Invoice invoice = StringUtils.isNotEmpty(invoiceTitle) ? new Invoice(invoiceTitle, invoiceTaxNumber, null) : null;

        Set<CartItem> carts=cart.getCartItems();
        Set<CartItem>  copy=new HashSet<CartItem>();
        for (CartItem c:carts){
            if (c.getIsBuy()==1){
                copy.add(c);
            }
        }
        cart.setCartItems(copy);

        List<Order> orders = orderService.generate(orderType, cart, receiver, paymentMethod, shippingMethod, invoice, balance, memo);

        BigDecimal price = BigDecimal.ZERO;
        BigDecimal fee = BigDecimal.ZERO;
        BigDecimal freight = BigDecimal.ZERO;
        BigDecimal tax = BigDecimal.ZERO;
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal amountPayable = BigDecimal.ZERO;
        Long rewardPoint = 0L;
        Long exchangePoint = 0L;
        boolean isDelivery = false;

        for (Order order : orders) {
            price = price.add(order.getPrice());
            fee = fee.add(order.getFee());
            freight = freight.add(order.getFreight());
            tax = tax.add(order.getTax());
            amount = amount.add(order.getAmount());
            amountPayable = amountPayable.add(order.getAmountPayable());
            rewardPoint = rewardPoint + order.getRewardPoint();
            exchangePoint = exchangePoint + order.getExchangePoint();
            if (order.getIsDelivery()) {
                isDelivery = true;
            }
        }

        data.put("price", price);
        data.put("fee", fee);
        data.put("freight", freight);
        data.put("tax", tax);
        data.put("amount", amount);
        data.put("amountPayable", amountPayable);
        data.put("rewardPoint", rewardPoint);
        data.put("exchangePoint", exchangePoint);
        data.put("isDelivery", isDelivery);
        return ResponseEntity.ok(data);
    }

    /**
     * 创建
     */
    @PostMapping("/create")
    public ResponseEntity<?> create(Long skuId, Integer quantity, String cartTag, Long receiverId, Long paymentMethodId, Long shippingMethodId, String code, String invoiceTitle, String invoiceTaxNumber, BigDecimal balance, String memo, @CurrentUser Member currentUser,
                                    @CurrentCart Cart currentCart,String dataSource) {
        Map<String, Object> data = new HashMap<>();
        Cart cart;
        Order.Type orderType;
        if (skuId != null) {
            Sku sku = skuService.find(skuId);
            if (sku == null) {
                return Results.UNPROCESSABLE_ENTITY;
            }
            if (Product.Type.GIFT.equals(sku.getType())) {
                return Results.UNPROCESSABLE_ENTITY;
            }
            if (quantity == null || quantity < 1) {
                return Results.UNPROCESSABLE_ENTITY;
            }

            cart = generateCart(currentUser, sku, quantity);

            switch (sku.getType()) {
                case GENERAL:
                    orderType = Order.Type.GENERAL;
                    break;
                case EXCHANGE:
                    orderType = Order.Type.EXCHANGE;
                    break;
                default:
                    orderType = null;
                    break;
            }
        } else {
            cart = currentCart;
            orderType = Order.Type.GENERAL;
        }

        if (cart == null || cart.isEmpty()) {
            return Results.UNPROCESSABLE_ENTITY;
        }

        Set<CartItem> cartItemSet =cart.getCartItems();
        Set<CartItem>  itemSet=new HashSet<CartItem>();
        for (CartItem c:cartItemSet){
            if (c.getIsBuy()==1){
                itemSet.add(c);
            }
        }
        cart.setCartItems(itemSet);

        if (cartTag != null && !StringUtils.equals(cart.getTag(), cartTag)) {
            return Results.unprocessableEntity("shop.order.cartHasChanged");
        }
        if (cart.hasNotActive()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (cart.hasNotMarketable()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (cart.hasLowStock()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (cart.hasExpiredProduct()) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (orderType == null) {
            return Results.UNPROCESSABLE_ENTITY;
        }

        for (CartItem c:itemSet) {
            if(c.getPrice().compareTo(BigDecimal.ZERO)<=0){
                String  msg = "编号为" + c.getSku().getProduct().getInternalNumber() + "的商品:" + c.getSku().getProduct().getName() + "暂时无法购买，请选择其他商品。";
                ResponseEntity<Map<String, String>> UNPROCESSABLE_ENTITY = Results.unprocessableEntity(msg);
                return UNPROCESSABLE_ENTITY;
            }
        }


        Receiver receiver = cart.getIsDelivery() ? receiverService.find(receiverId) : null;
        if (cart.getIsDelivery() && (receiver == null || !currentUser.equals(receiver.getMember()))) {
            return Results.UNPROCESSABLE_ENTITY;
        }else{

            String areaId= String.valueOf(receiver.getArea().getId());
            boolean  bool=false;
            Area a=  areaService.find(receiver.getArea().getId());
            String threePath = a.getTreePath();
            //用户所有的areaId
            String areaIds=threePath+areaId;
            String msg="";
            int i=0;
            for (CartItem c:itemSet) {
                 //商品的areaId
                 String s = c.getSku().getProduct().getAreaIds();
                 List<String> same = new ArrayList<>();
                 if(s != null){
                     String [] a1= areaIds.split(",");
                     String [] a2= s.split(",");
                     for (String str : a1) {
                         if (Arrays.binarySearch(a2, str) >= 0) {
                             same.add(str);
                         }
                     }
                 }
                 if(same.size()>0||s==null){
                     bool=true;
                     i++;
                 }
                 if(same.size()==0&&s!=null){
                     msg = "编号为" + c.getSku().getProduct().getInternalNumber() + "的商品:" + c.getSku().getProduct().getName() + "不在配送范围内，请选择其他商品。";
                     break;
                 }

            }
            Boolean f=false;
            if(itemSet.size()==1&&!bool){
                //没权限
                f=true;
            }
            if(itemSet.size()>0&&i!=itemSet.size()){
                //没权限
                f=true;
            }
            if(f){
                ResponseEntity<Map<String, String>> UNPROCESSABLE_ENTITY = Results.unprocessableEntity(msg);
                return UNPROCESSABLE_ENTITY;
            }


        }
        if (balance != null && balance.compareTo(BigDecimal.ZERO) < 0) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        if (balance != null && balance.compareTo(currentUser.getAvailableBalance()) > 0) {
            return Results.unprocessableEntity("shop.order.insufficientBalance");
        }
        if (currentUser.getPoint() < cart.getExchangePoint()) {
            return Results.unprocessableEntity("shop.order.lowPoint");
        }
        PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
        if (cart.contains(Store.Type.GENERAL) && paymentMethod != null && PaymentMethod.Method.OFFLINE.equals(paymentMethod.getMethod())) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
        if (cart.getIsDelivery() && shippingMethod == null) {
            return Results.UNPROCESSABLE_ENTITY;
        }

        Invoice invoice = StringUtils.isNotEmpty(invoiceTitle) ? new Invoice(invoiceTitle, invoiceTaxNumber, null) : null;
        List<Order> orders = orderService.create(orderType, cart, receiver, paymentMethod, shippingMethod, invoice, balance, memo,dataSource);
        List<String> orderSns = new ArrayList<>();
        for (Order order : orders) {
            if (order != null && order.getAmount().compareTo(order.getAmountPaid()) > 0 && order.getAmountPayable().compareTo(BigDecimal.ZERO) > 0) {
                orderSns.add(order.getSn());
            }
        }
        data.put("orderSns", orderSns);
        return ResponseEntity.ok(data);
    }


    public     void calculationOrder(String orderSn){

        Order order = orderService.findBySn(orderSn);
        List<OrderItem> orderItemList=order.getOrderItems();
        Cart  cart=cartService.create();
        for (OrderItem orderItem:orderItemList){
            Sku sku=skuService.find(orderItem.getSku().getId());
            CartItem cartItem= new CartItem();
            cartItem=new CartItem();
            cartItem.setQuantity(orderItem.getQuantity());
            cartItem.setCart(cart);
            cartItem.setSku(sku);
            cartItem.setIsBuy(1);
            cartItemService.save(cartItem);
        }
        orderService.calculationOrder(cart,order.getId());
    }


    /**
     * 支付
     */
    @GetMapping("/payment")
    public String payment(String[] orderSns, @CurrentUser Member currentUser, ModelMap model) {
        if (ArrayUtils.isEmpty(orderSns)) {
            return UNPROCESSABLE_ENTITY_VIEW;
        }

        List<PaymentPlugin> paymentPlugins = pluginService.getActivePaymentPlugins(WebUtils.getRequest());
        PaymentPlugin defaultPaymentPlugin = null;
        PaymentMethod orderPaymentMethod = null;
        BigDecimal fee = BigDecimal.ZERO;
        BigDecimal amount = BigDecimal.ZERO;
        boolean online = false;
        List<Order> orders = new ArrayList<>();
        for (String orderSn : orderSns) {
            Order order = orderService.findBySn(orderSn);
            if (order == null) {
                return UNPROCESSABLE_ENTITY_VIEW;
            }
            BigDecimal amountPayable = order.getAmountPayable();
            if (order.getAmount().compareTo(order.getAmountPaid()) <= 0 || amountPayable.compareTo(BigDecimal.ZERO) <= 0) {
                return "redirect:/member/order/list";
            }
            orderPaymentMethod = order.getPaymentMethod();
            if (!currentUser.equals(order.getMember()) || orderPaymentMethod == null) {
                return UNPROCESSABLE_ENTITY_VIEW;
            }
            if (PaymentMethod.Method.ONLINE.equals(orderPaymentMethod.getMethod())) {
                if (!orderService.acquireLock(order, currentUser)) {
                    return "redirect:/member/order/list";
                }
                if (CollectionUtils.isNotEmpty(paymentPlugins)) {
                    defaultPaymentPlugin = paymentPlugins.get(2);
                }
                online = true;
            } else {
                fee = fee.add(order.getFee());
                online = false;
            }
            amount = amount.add(amountPayable);
            orders.add(order);
        }
        if (online && defaultPaymentPlugin != null) {
            fee = defaultPaymentPlugin.calculateFee(amount).add(fee);
            amount = fee.add(amount);
            model.addAttribute("online", online);
            model.addAttribute("defaultPaymentPlugin", defaultPaymentPlugin);
            model.addAttribute("paymentPlugins", paymentPlugins);
        }
        if (CollectionUtils.isNotEmpty(orders)) {
            Order order = orders.get(0);
            model.addAttribute("shippingMethodName", order.getShippingMethodName());
            model.addAttribute("paymentMethodName", order.getPaymentMethodName());
            model.addAttribute("paymentMethod", orderPaymentMethod);
            model.addAttribute("expireDate", order.getExpire());
        }
        model.addAttribute("fee", fee);
        model.addAttribute("amount", amount);
        model.addAttribute("orders", orders);
        model.addAttribute("orderSns", Arrays.asList(orderSns));
        return "shop/order/payment";
    }

    /**
     * 计算支付金额
     */
    @GetMapping("/calculate_amount")
    public ResponseEntity<?> calculateAmount(String paymentPluginId, String[] orderSns, @CurrentUser Member currentUser) {
        Map<String, Object> data = new HashMap<>();
        if (ArrayUtils.isEmpty(orderSns)) {
            return Results.UNPROCESSABLE_ENTITY;
        }
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
        BigDecimal amount = BigDecimal.ZERO;
        for (String orderSn : orderSns) {
            Order order = orderService.findBySn(orderSn);
            if (order == null || !currentUser.equals(order.getMember()) || paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
                return Results.UNPROCESSABLE_ENTITY;
            }
            amount = amount.add(order.getAmountPayable());
        }
        BigDecimal fee = paymentPlugin.calculateFee(amount);
        data.put("fee", fee);
        data.put("amount", amount.add(fee));
        return ResponseEntity.ok(data);
    }

    /**
     * 生成购物车
     *
     * @param member   会员
     * @param sku      SKU
     * @param quantity 数量
     * @return 购物车
     */
    public Cart generateCart(Member member, Sku sku, Integer quantity) {
        Assert.notNull(member, "[Assertion failed] - member is required; it must not be null");
        Assert.notNull(sku, "[Assertion failed] - sku is required; it must not be null");
        Assert.state(!Product.Type.GIFT.equals(sku.getType()), "[Assertion failed] - sku type can't be GIFT");
        Assert.notNull(quantity, "[Assertion failed] - quantity is required; it must not be null");
        Assert.state(quantity > 0, "[Assertion failed] - quantity must be greater than 0");

        Cart cart = new Cart();
        Set<CartItem> cartItems = new HashSet<>();
        CartItem cartItem = new CartItem();
        cartItem.setSku(sku);
        cartItem.setQuantity(quantity);
        cartItem.setIsBuy(1);
        cartItems.add(cartItem);
        cartItem.setCart(cart);
        cart.setMember(member);
        cart.setCartItems(cartItems);
        return cart;
    }


    /**
     * 使用余额一键付款
     */
    @PostMapping("/payAmount")
    public ResponseEntity<?> calculateAmount(Long orderId, @CurrentUser Member currentUser) {
        Map<String, Object> data = new HashMap<>();
        Order order= orderService.find(orderId);
        if(order==null){
            return Results.UNPROCESSABLE_ENTITY;
        }

        //查询订单下面的库存是否足够
        List<OrderItem> orderItemList= order.getOrderItems();
        Boolean  flag=false;
        String  msg="";
        for (OrderItem orderItem:orderItemList){
            if(orderItem.getQuantity()>orderItem.getSku().getAvailableStock()){
                msg= "编号为" + orderItem.getSku().getProduct().getInternalNumber() + "的商品:" + orderItem.getSku().getProduct().getName() + "库存不足，暂时无法完成付款。";
                flag=true;
                break;
            }
        }
        if(flag){
            ResponseEntity<Map<String, String>> UNPROCESSABLE_ENTITY = Results.unprocessableEntity(msg);
            return UNPROCESSABLE_ENTITY;
        }

        String  type="0";
        //用户余额
        BigDecimal balance= currentUser.getBalance();
        //总金额
        BigDecimal amount=order.getAmount();
        //已付金额
        BigDecimal amountPaid=order.getAmountPaid();
        //未付
        BigDecimal wfAmount=amount.subtract(amountPaid);
        //账户余额够付
        if(balance.compareTo(wfAmount)==1){
            //扣掉用户余额
            currentUser.setBalance(currentUser.getBalance().subtract(wfAmount));
            memberService.update(currentUser);
            order.setAmountPaid(amount);
            if(orderService.statusUpdate(order,"PC余额支付")) {
                order.setStatus(Order.Status.PENDING_REVIEW);
                orderService.update(order);
            }


            OrderPayment orderPayment = new OrderPayment();
            orderPayment.setMethod(OrderPayment.Method.DEPOSIT);
            orderPayment.setFee(BigDecimal.ZERO);
            orderPayment.setOrder(order);
            orderPayment.setAmount(wfAmount);
            orderPayment.setPaymentMethod(JIFEN_CARD_DESN);
            orderPayment.setPayer(String.valueOf(order.getMember().getId()));

            orderPayment.setSn(snService.generate(Sn.Type.ORDER_PAYMENT));
            orderPayment.setOrder(order);
            orderPaymentService.save(orderPayment);


            MemberDepositLog memberDepositLog = new MemberDepositLog();
            memberDepositLog.setId(IdWorker.getId());
            memberDepositLog.setVersion(0L);
            memberDepositLog.setCreatedDate(new Date());
            memberDepositLog.setType(MemberDepositLog.Type.ORDER_PAYMENT);
            memberDepositLog.setCredit(BigDecimal.ZERO);
            memberDepositLog.setDebit(wfAmount);
            memberDepositLog.setBalance(currentUser.getBalance());
            memberDepositLog.setMemo("积分卡余额支付"+currentUser.getAttributeValue0());
            memberDepositLog.setMember(currentUser);
            memberDepositLog.setOrders(order.getId());
//            memberDepositLog.setCardNo(currentUser.getAttributeValue0());
            memberDepositLogService.insert(memberDepositLog);

            //上传数据到中台
            if(order.getStatus().equals(Order.Status.PENDING_REVIEW)&&order.getAmount().compareTo(order.getAmountPaid())==0){
                erpSyncService.uploadOrder(order.getSn());
            }

            msg="您已经使用余额￥"+wfAmount.setScale(2, RoundingMode.HALF_UP)+"付款成功。";
            type="1";

        }else{
            msg="您当前账户余额￥"+balance.setScale(2, RoundingMode.HALF_UP)+"不够支付商品剩余未支付余额，请充值。";
        }
        data.put("msg", msg);
        data.put("type", type);
        return ResponseEntity.ok(data);
    }

    /**
     * 订单复购
     */
    @PostMapping("/orderAdd")
    public ResponseEntity<?> orderAdd(Long orderId, @CurrentUser Member currentUser) {
        Map<String, Object> data = new HashMap<>();
        Order order= orderService.find(orderId);
        if(order==null){
            return Results.UNPROCESSABLE_ENTITY;
        }
        List<OrderItem> orderItemList=order.getOrderItems();
        Cart   cart=cartService.getCurrent();
        if(cart==null){
            cart=cartService.create();
        }
        for (OrderItem orderItem:orderItemList){
            Sku sku=skuService.find(orderItem.getSku().getId());
            CartItem cartItem= cartItemService.fingItemBySkuId(sku.getId(),cart.getId());
            if(cartItem!=null){
                cartItem.setQuantity(cartItem.getQuantity()+1);
                cartItemService.update(cartItem);
            }else{
                cartItem=new CartItem();
                cartItem.setQuantity(1);
                cartItem.setCart(cart);
                cartItem.setSku(sku);
                cartItem.setIsBuy(1);
                cartItemService.save(cartItem);
            }
        }

        return Results.OK;
    }


}